<template>
  <el-container>
    <el-aside width="600px">
      <div class="left-top">
        <el-input
            v-model="keywords"
            class="api-search"
            placeholder="请输入接口名称">
          <template #suffix>
            <el-icon :size="20" class="el-input__icon">
              <Search/>
            </el-icon>
          </template>
        </el-input>
      </div>
      <div class="left-list" v-infinite-scroll="loadData">
        <div class="list-item" v-for="(item,index) in list" :key="index">
          <div class="path" @click="current=item" :class="{active:current.path===item.path}">{{ item.path }}</div>
        </div>
      </div>

    </el-aside>
    <el-main>
      <div>
        <el-input v-model="current.path" placeholder="请输入接口路径"/>
      </div>
      <div class="code-editor">
        <CodeEditor v-model="current.response" editor-id="jsonCode" height="100%"/>
      </div>
      <div class="btn-box">
        <el-row :gutter="20">
          <el-col :span="2">
            <el-button type="success" @click="addApi">新增</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="danger" :disabled="!current._id" @click="delApi">删除</el-button>
          </el-col>
          <el-col :span="2">
            <div class="state-box">
              <el-checkbox v-model="current.state">启用</el-checkbox>
            </div>
          </el-col>
          <el-col :span="2" :offset="7">
            <div class="state-box">
              <el-checkbox v-model="strictMatch">严格匹配</el-checkbox>
            </div>
          </el-col>
          <el-col :span="2" :offset="1">
            <div class="state-box">
              <el-checkbox v-model="autoSave">录制接口</el-checkbox>
            </div>
          </el-col>
          <el-col :span="2" :offset="2">
            <el-button type="primary" v-if="current._id" @click="updateApi">更新</el-button>
            <el-button type="primary" v-else @click="saveApi">保存</el-button>
          </el-col>
        </el-row>

      </div>
    </el-main>
  </el-container>
</template>
<script>
import request from "@/utils/request.js";
import CodeEditor from '@/components/CodeEditor.vue';

export default {
  name: 'HomeView',
  components: {
    CodeEditor,
  },
  data() {
    return {
      timer: null,
      keywords: '',
      list: [],
      current: {},
      page: 1,
      limit: 20,
      total: 0,
      autoSave: false,
      strictMatch:false

    }
  },
  watch: {
    keywords() {
      this.getList()
    },
    autoSave(){
      this.sysConfig('AUTO_SAVE',this.autoSave)
    },
    strictMatch(){
      this.sysConfig('STRICT_MATCH',this.strictMatch)
    }
  },
  methods: {
    getList() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.list = []
        this.current = {}
        this.page = 0
        this.total = 0
        this.loadData()
      }, 500)

    },
    loadData() {
      if (this.page === 0 || this.list.length < this.total) {
        this.page++
        let params = {
          page: this.page,
          limit: this.limit,
          path: this.keywords
        }
        request.post('/sys/page', params).then(({data, total}) => {
          this.list = [...this.list, ...data]
          this.total = total
        })
      }

    },
    addApi() {
      this.current = {
        path: '',
        response: JSON.stringify({
          code: 0,
          data: {},
          resultMsg: ""
        }),
        state: true
      }
    },
    delApi() {
      if (this.current._id) {
        request.post(`/sys/delete`, {
          _id: this.current._id,
          path: this.current.path
        }).then(() => {
          this.getList()
        })
      }
    },
    saveApi() {
      if (!this.current.path) {
        this.$message({
          message: '接口名称不能为空',
          type: 'warning'
        });
        return
      }
      if (!this.current.response) {
        this.$message({
          message: '接口响应数据不能为空',
          type: 'warning'
        });
        return
      }
      if (!this.isValidJson(this.current.response)) {
        this.$message({
          message: '接口数据格式错误',
          type: 'warning'
        });
        return
      }

      request.post(`/sys/api`, this.current).then(() => {
        this.getList()
      })

    },
    updateApi() {
      if (this.current._id) {
        request.post("/sys/update", this.current).then(() => {
          this.getList()
        })
      }
    },
    isValidJson(str) {
      try {
        JSON.parse(str);
      } catch (e) {
        return false;
      }
      return true;
    },
    //获取、保存系统配置值
    async sysConfig(prop,value) {
      if(prop){
        const {data} = await request.post("/sys/config", {prop,value});
        return data
      }
    },
  },
  mounted() {
    this.getList()
    this.sysConfig('AUTO_SAVE').then((data)=>{
      this.autoSave = data
    })
    this.sysConfig('STRICT_MATCH').then((data)=>{
      this.strictMatch = data
    })
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.full-height {
  height: 100vh;
}

.api-search {
  width: 550px;
  margin: 10px;
}

.left-list {
  height: calc(100vh - 100px);
  overflow: auto;

  .list-item {
    cursor: pointer;
    margin: 5px;
    line-height: 30px;
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #eef2f6;

    &:hover {
      background-color: #f5f7fa;
    }

    .active {
      color: #409EFF;
    }
  }
}

.code-editor {
  box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.4);
  height: calc(100% - 100px);
}

.btn-box {
  margin-top: 20px;
  .state-box{
    margin-top: 10px;
  }

}
</style>
